package com.cnsugar.common.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.Serializable;

/**
 * Spring容器
 *
 * @Author Sugar
 * @Version 2018/12/7 14:09
 */
public class AppContext implements Serializable {

    protected static ApplicationContext applicationContext = null;

    private static Logger logger = LoggerFactory.getLogger(AppContext.class);

    /**
     * 在WEB项目中可以使用WebApplicationContextUtils.getWebApplicationContext(servletContext)获取Context进行初始化，以便与Web容器使用同一个Context;
     *
     * @param context
     */
    public static void initApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }


    /**
     * 重新初始化
     */
    public static void initApplicationContext() {
        applicationContext = null;
        getApplicationContext();
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            synchronized (AppContext.class) {
                if (applicationContext != null) {
                    return applicationContext;
                }
                logger.info("!!! ApplicationContext未初始化，自动加载：classpath*:/**/spring-context*.xml");
                try {
                    applicationContext = new ClassPathXmlApplicationContext(new String[]{
                            "classpath*:/**/spring-context*.xml"});
                } catch (BeansException e) {
                    e.printStackTrace();
                }
            }
        }

        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String name) {
        try {
            return (T) getApplicationContext().getBean(name);
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return null;
    }
}